<template>
  <div class="profile-settings">
    <div class="settings-header">
      <h2>个人设置</h2>
      <p>管理您的个人信息和账户设置</p>
    </div>

    <el-tabs v-model="activeTab" class="settings-tabs">
      <!-- 基本信息 -->
      <el-tab-pane label="基本信息" name="basic">
        <div class="settings-section">
          <h3>个人信息</h3>
          <el-form
            :model="profileForm"
            :rules="profileRules"
            ref="profileFormRef"
            label-width="100px"
            class="profile-form"
          >
            <el-form-item label="头像">
              <div class="avatar-upload">
                <el-upload
                  class="avatar-uploader"
                  action="#"
                  :show-file-list="false"
                  :before-upload="beforeAvatarUpload"
                  :http-request="uploadAvatar"
                >
                  <img v-if="profileForm.avatar" :src="profileForm.avatar" class="avatar" />
                  <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                </el-upload>
                <div class="avatar-tips">
                  <p>支持 JPG、PNG 格式</p>
                  <p>文件大小不超过 2MB</p>
                </div>
              </div>
            </el-form-item>

            <el-form-item label="昵称" prop="nickname">
              <el-input v-model="profileForm.nickname" placeholder="请输入昵称" />
            </el-form-item>

            <el-form-item label="性别">
              <el-radio-group v-model="profileForm.gender">
                <el-radio :value="1">男</el-radio>
                <el-radio :value="2">女</el-radio>
                <el-radio :value="0">保密</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="生日">
              <el-date-picker
                v-model="profileForm.birthday"
                type="date"
                placeholder="选择生日"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>

            <el-form-item label="手机号" prop="mobile">
              <el-input
                v-model="profileForm.mobile"
                placeholder="请输入手机号"
                :disabled="true"
              >
                <template #append>
                  <el-button @click="showChangeMobile = true">更换</el-button>
                </template>
              </el-input>
            </el-form-item>

            <el-form-item label="邮箱" prop="email">
              <el-input v-model="profileForm.email" placeholder="请输入邮箱地址" />
            </el-form-item>

            <el-form-item label="个人简介">
              <el-input
                v-model="profileForm.bio"
                type="textarea"
                :rows="3"
                placeholder="介绍一下自己..."
                maxlength="200"
                show-word-limit
              />
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="updateProfile" :loading="saving">
                保存修改
              </el-button>
              <el-button @click="resetProfileForm">取消</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-tab-pane>

      <!-- 账户安全 -->
      <el-tab-pane label="账户安全" name="security">
        <div class="settings-section">
          <h3>密码设置</h3>
          <el-form
            :model="passwordForm"
            :rules="passwordRules"
            ref="passwordFormRef"
            label-width="100px"
            class="password-form"
          >
            <el-form-item label="当前密码" prop="oldPassword">
              <el-input
                v-model="passwordForm.oldPassword"
                type="password"
                placeholder="请输入当前密码"
                show-password
              />
            </el-form-item>

            <el-form-item label="新密码" prop="newPassword">
              <el-input
                v-model="passwordForm.newPassword"
                type="password"
                placeholder="请输入新密码"
                show-password
              />
            </el-form-item>

            <el-form-item label="确认密码" prop="confirmPassword">
              <el-input
                v-model="passwordForm.confirmPassword"
                type="password"
                placeholder="请再次输入新密码"
                show-password
              />
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="changePassword" :loading="changingPassword">
                修改密码
              </el-button>
              <el-button @click="resetPasswordForm">取消</el-button>
            </el-form-item>
          </el-form>

          <div class="security-info">
            <h3>账户安全信息</h3>
            <div class="security-item">
              <div class="security-label">
                <el-icon><Lock /></el-icon>
                <span>登录密码</span>
              </div>
              <div class="security-status">
                <span class="status-text success">已设置</span>
                <el-button text type="primary">修改</el-button>
              </div>
            </div>

            <div class="security-item">
              <div class="security-label">
                <el-icon><Message /></el-icon>
                <span>手机号码</span>
              </div>
              <div class="security-status">
                <span class="status-text">{{ maskPhone(userStore.userInfo?.mobile) }}</span>
                <el-button text type="primary" @click="showChangeMobile = true">更换</el-button>
              </div>
            </div>

            <div class="security-item">
              <div class="security-label">
                <el-icon><User /></el-icon>
                <span>实名认证</span>
              </div>
              <div class="security-status">
                <span class="status-text" :class="userStore.isIdentityVerified ? 'success' : 'warning'">
                  {{ userStore.isIdentityVerified ? '已认证' : '未认证' }}
                </span>
                <el-button 
                  text 
                  type="primary" 
                  @click="$router.push('/profile/identity')"
                  v-if="!userStore.isIdentityVerified"
                >
                  去认证
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </el-tab-pane>

      <!-- 隐私设置 -->
      <el-tab-pane label="隐私设置" name="privacy">
        <div class="settings-section">
          <h3>隐私设置</h3>
          <div class="privacy-settings">
            <div class="privacy-item">
              <div class="privacy-info">
                <h4>个人资料可见性</h4>
                <p>控制其他用户可以看到您的哪些信息</p>
              </div>
              <el-switch
                v-model="privacySettings.profileVisible"
                @change="updatePrivacySettings"
              />
            </div>

            <div class="privacy-item">
              <div class="privacy-info">
                <h4>订单历史可见</h4>
                <p>是否允许商家查看您的历史订单</p>
              </div>
              <el-switch
                v-model="privacySettings.orderHistoryVisible"
                @change="updatePrivacySettings"
              />
            </div>

            <div class="privacy-item">
              <div class="privacy-info">
                <h4>接收营销信息</h4>
                <p>是否接收优惠活动和营销推广信息</p>
              </div>
              <el-switch
                v-model="privacySettings.allowMarketing"
                @change="updatePrivacySettings"
              />
            </div>

            <div class="privacy-item">
              <div class="privacy-info">
                <h4>位置信息收集</h4>
                <p>允许收集位置信息以提供更好的服务</p>
              </div>
              <el-switch
                v-model="privacySettings.allowLocation"
                @change="updatePrivacySettings"
              />
            </div>
          </div>
        </div>
      </el-tab-pane>

      <!-- 通知设置 -->
      <el-tab-pane label="通知设置" name="notifications">
        <div class="settings-section">
          <h3>消息通知</h3>
          <div class="notification-settings">
            <div class="notification-group">
              <h4>订单通知</h4>
              <div class="notification-item">
                <span>订单状态变更</span>
                <el-switch v-model="notificationSettings.orderStatus" />
              </div>
              <div class="notification-item">
                <span>订单评价提醒</span>
                <el-switch v-model="notificationSettings.orderReview" />
              </div>
              <div class="notification-item">
                <span>配送通知</span>
                <el-switch v-model="notificationSettings.delivery" />
              </div>
            </div>

            <div class="notification-group">
              <h4>营销通知</h4>
              <div class="notification-item">
                <span>优惠券到期提醒</span>
                <el-switch v-model="notificationSettings.couponExpiry" />
              </div>
              <div class="notification-item">
                <span>促销活动通知</span>
                <el-switch v-model="notificationSettings.promotions" />
              </div>
              <div class="notification-item">
                <span>新服务上线</span>
                <el-switch v-model="notificationSettings.newServices" />
              </div>
            </div>

            <div class="notification-group">
              <h4>系统通知</h4>
              <div class="notification-item">
                <span>系统维护通知</span>
                <el-switch v-model="notificationSettings.systemMaintenance" />
              </div>
              <div class="notification-item">
                <span>安全提醒</span>
                <el-switch v-model="notificationSettings.security" />
              </div>
            </div>

            <el-button type="primary" @click="saveNotificationSettings" :loading="savingNotifications">
              保存设置
            </el-button>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 更换手机号对话框 -->
    <el-dialog v-model="showChangeMobile" title="更换手机号" width="400px">
      <el-form :model="mobileForm" :rules="mobileRules" ref="mobileFormRef" label-width="80px">
        <el-form-item label="新手机号" prop="newMobile">
          <el-input v-model="mobileForm.newMobile" placeholder="请输入新手机号" />
        </el-form-item>
        <el-form-item label="验证码" prop="code">
          <div style="display: flex; gap: 10px;">
            <el-input v-model="mobileForm.code" placeholder="请输入验证码" />
            <el-button @click="sendMobileCode" :disabled="mobileCountdown > 0">
              {{ mobileCountdown > 0 ? `${mobileCountdown}秒后重发` : '发送验证码' }}
            </el-button>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showChangeMobile = false">取消</el-button>
        <el-button type="primary" @click="changeMobile" :loading="changingMobile">
          确认更换
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useUserStore } from '@/stores/user'
import { userApi, authApi, settingsApi } from '@/services/api'
import { ElMessage } from 'element-plus'
import { Plus, Lock, Message, User } from '@element-plus/icons-vue'

const userStore = useUserStore()
const activeTab = ref('basic')
const saving = ref(false)
const changingPassword = ref(false)
const savingNotifications = ref(false)
const changingMobile = ref(false)
const showChangeMobile = ref(false)
const mobileCountdown = ref(0)

const profileFormRef = ref()
const passwordFormRef = ref()
const mobileFormRef = ref()

// 个人信息表单
const profileForm = reactive({
  avatar: '',
  nickname: '',
  gender: 0,
  birthday: '',
  mobile: '',
  email: '',
  bio: ''
})

// 密码修改表单
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 手机号更换表单
const mobileForm = reactive({
  newMobile: '',
  code: ''
})

// 隐私设置
const privacySettings = reactive({
  profileVisible: true,
  orderHistoryVisible: true,
  allowMarketing: true,
  allowLocation: true
})

// 通知设置
const notificationSettings = reactive({
  orderStatus: true,
  orderReview: true,
  delivery: true,
  couponExpiry: true,
  promotions: false,
  newServices: false,
  systemMaintenance: true,
  security: true
})

// 表单验证规则
const profileRules = {
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 2, max: 20, message: '昵称长度为2-20个字符', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
}

const validateNewPassword = (rule, value, callback) => {
  if (value.length < 6) {
    callback(new Error('密码至少6位'))
  } else {
    callback()
  }
}

const validateConfirmPassword = (rule, value, callback) => {
  if (value !== passwordForm.newPassword) {
    callback(new Error('两次输入密码不一致'))
  } else {
    callback()
  }
}

const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { validator: validateNewPassword, trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    { validator: validateConfirmPassword, trigger: 'blur' }
  ]
}

const mobileRules = {
  newMobile: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' }
  ]
}

// 初始化数据
const initData = async () => {
  try {
    // 获取用户信息
    const userInfo = userStore.userInfo
    if (userInfo) {
      Object.assign(profileForm, {
        avatar: userInfo.avatar || '',
        nickname: userInfo.nickname || '',
        gender: userInfo.gender || 0,
        birthday: userInfo.birthday || '',
        mobile: userInfo.mobile || '',
        email: userInfo.email || '',
        bio: userInfo.bio || ''
      })
    }

    // 获取隐私设置
    try {
      const privacyResponse = await settingsApi.getPrivacySettings()
      Object.assign(privacySettings, privacyResponse.data)
    } catch (error) {
      console.log('隐私设置API暂未实现，使用默认值')
    }

  } catch (error) {
    console.error('初始化数据失败:', error)
  }
}

// 头像上传前验证
const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('头像只能是 JPG/PNG 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('头像大小不能超过 2MB!')
    return false
  }
  return true
}

// 上传头像
const uploadAvatar = async (options) => {
  try {
    // 这里应该调用实际的文件上传API
    // const formData = new FormData()
    // formData.append('file', options.file)
    // const response = await uploadApi.uploadFile(formData)
    // profileForm.avatar = response.data.url
    
    // 模拟上传成功
    const reader = new FileReader()
    reader.onload = (e) => {
      profileForm.avatar = e.target.result
    }
    reader.readAsDataURL(options.file)
    
    ElMessage.success('头像上传成功')
  } catch (error) {
    ElMessage.error('头像上传失败')
  }
}

// 更新个人信息
const updateProfile = async () => {
  try {
    await profileFormRef.value.validate()
    saving.value = true
    
    await userStore.updateProfile(profileForm)
    ElMessage.success('个人信息更新成功')
    
  } catch (error) {
    if (error !== 'validation failed') {
      ElMessage.error('更新失败: ' + (error.message || '未知错误'))
    }
  } finally {
    saving.value = false
  }
}

// 重置个人信息表单
const resetProfileForm = () => {
  initData()
}

// 修改密码
const changePassword = async () => {
  try {
    await passwordFormRef.value.validate()
    changingPassword.value = true
    
    await userStore.changePassword({
      oldPassword: passwordForm.oldPassword,
      newPassword: passwordForm.newPassword
    })
    
    ElMessage.success('密码修改成功')
    resetPasswordForm()
    
  } catch (error) {
    if (error !== 'validation failed') {
      ElMessage.error('密码修改失败: ' + (error.message || '未知错误'))
    }
  } finally {
    changingPassword.value = false
  }
}

// 重置密码表单
const resetPasswordForm = () => {
  passwordForm.oldPassword = ''
  passwordForm.newPassword = ''
  passwordForm.confirmPassword = ''
  passwordFormRef.value?.clearValidate()
}

// 发送手机验证码
const sendMobileCode = async () => {
  if (!mobileForm.newMobile) {
    ElMessage.warning('请先输入新手机号')
    return
  }

  try {
    await authApi.sendSmsCode(mobileForm.newMobile)
    ElMessage.success('验证码已发送')
    
    // 开始倒计时
    mobileCountdown.value = 60
    const timer = setInterval(() => {
      mobileCountdown.value--
      if (mobileCountdown.value <= 0) {
        clearInterval(timer)
      }
    }, 1000)
  } catch (error) {
    ElMessage.error('发送验证码失败')
  }
}

// 更换手机号
const changeMobile = async () => {
  try {
    await mobileFormRef.value.validate()
    changingMobile.value = true
    
    // 这里应该调用更换手机号的API
    // await userApi.changeMobile(mobileForm)
    
    profileForm.mobile = mobileForm.newMobile
    ElMessage.success('手机号更换成功')
    showChangeMobile.value = false
    mobileForm.newMobile = ''
    mobileForm.code = ''
    
  } catch (error) {
    if (error !== 'validation failed') {
      ElMessage.error('更换失败: ' + (error.message || '未知错误'))
    }
  } finally {
    changingMobile.value = false
  }
}

// 更新隐私设置
const updatePrivacySettings = async () => {
  try {
    await settingsApi.updatePrivacySettings(privacySettings)
    ElMessage.success('隐私设置已更新')
  } catch (error) {
    console.log('隐私设置API暂未实现')
    ElMessage.success('隐私设置已更新（本地保存）')
  }
}

// 保存通知设置
const saveNotificationSettings = async () => {
  try {
    savingNotifications.value = true
    // 这里应该调用保存通知设置的API
    await settingsApi.updateNotificationSettings(notificationSettings)
    ElMessage.success('通知设置已保存')
  } catch (error) {
    ElMessage.error('保存失败')
  } finally {
    savingNotifications.value = false
  }
}

// 掩码手机号
const maskPhone = (phone) => {
  if (!phone) return ''
  return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
}

onMounted(() => {
  initData()
})
</script>

<style scoped>
.profile-settings {
  padding: 0;
}

.settings-header {
  margin-bottom: 30px;
  text-align: center;
}

.settings-header h2 {
  font-size: 24px;
  font-weight: 600;
  color: #333;
  margin-bottom: 8px;
}

.settings-header p {
  color: #666;
  font-size: 14px;
}

.settings-tabs {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.settings-section {
  max-width: 600px;
}

.settings-section h3 {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #f0f0f0;
}

.avatar-upload {
  display: flex;
  align-items: center;
  gap: 20px;
}

.avatar-uploader .avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  object-fit: cover;
}

.avatar-uploader .avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 80px;
  height: 80px;
  border: 2px dashed #d9d9d9;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: border-color 0.3s ease;
}

.avatar-uploader .avatar-uploader-icon:hover {
  border-color: #409eff;
  color: #409eff;
}

.avatar-tips {
  color: #999;
  font-size: 12px;
}

.avatar-tips p {
  margin: 2px 0;
}

.security-info {
  margin-top: 40px;
}

.security-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 0;
  border-bottom: 1px solid #f0f0f0;
}

.security-label {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #333;
  font-weight: 500;
}

.security-status {
  display: flex;
  align-items: center;
  gap: 12px;
}

.status-text {
  font-size: 14px;
}

.status-text.success {
  color: #67c23a;
}

.status-text.warning {
  color: #e6a23c;
}

.privacy-settings,
.notification-settings {
  max-width: 500px;
}

.privacy-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 0;
  border-bottom: 1px solid #f0f0f0;
}

.privacy-info h4 {
  margin: 0 0 4px 0;
  color: #333;
  font-size: 16px;
  font-weight: 500;
}

.privacy-info p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.notification-group {
  margin-bottom: 30px;
}

.notification-group h4 {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 1px solid #f0f0f0;
}

.notification-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  color: #333;
}

@media (max-width: 768px) {
  .settings-section {
    max-width: 100%;
  }
  
  .avatar-upload {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .security-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .security-status {
    width: 100%;
    justify-content: space-between;
  }
  
  .privacy-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
}
</style> 